import {Component, OnInit, ViewChild} from '@angular/core';
import {AlertComponent} from "../../unit/alert";
import {BarcodeScanner} from "@awesome-cordova-plugins/barcode-scanner/ngx";
import {Router} from "@angular/router";
// import {BarcodeScanner} from "@ionic-native/barcode-scanner/ngx";
// import {QRScanner, QRScannerStatus} from '@ionic-native/qr-scanner';

@Component({
    selector: 'app-scan-code',
    templateUrl: './scan-code.page.html',
    styleUrls: ['./scan-code.page.scss'],
})
export class ScanCodePage implements OnInit {

    constructor(private router: Router,
                private alertComponent: AlertComponent,
                private barcodeScanner: BarcodeScanner,
    ) {
    }

    ngOnInit() {
        this.startScan();
    }

    startScan() {
        this.barcodeScanner.scan({
            saveHistory: true, // Android, save scan history (default false)
            resultDisplayDuration: 500, // Android, display scanned text for X ms. 0 suppresses it entirely, default 1500
            formats: "QR_CODE,PDF_417", // default: all but PDF_417 and RSS_EXPANDED
        }).then(barcodeData => {
            if (barcodeData.text) {
                this.goToPage('code-info');
            } else {
                if (!barcodeData.cancelled) {
                    this.alertComponent.presentAlert('扫描失败').then();
                }
                history.go(-1);
            }
        }).catch(err => {
            this.alertComponent.presentAlert(err).then();
        });
    }

    goToPage(url) {
        const currentCard = localStorage.getItem('cardNumber');
        this.router.navigate([`/${url}`], {queryParams: {idCard: currentCard}}).then();
    }
}
